﻿using Microsoft.Extensions.Logging;
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _03Net8Logging.Customs
{
    public class MySQLLogger : ILogger
    {
        private string _connectionString { set; get; }

        public MySQLLogger(string connectionString)
        {
            _connectionString = connectionString;
        }


        public IDisposable? BeginScope<TState>(TState state) where TState : notnull
        {
            return null;
        }

        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }

        /// <summary>
        /// 1、将日志写到数据库
        /// </summary>
        /// <typeparam name="TState"></typeparam>
        /// <param name="logLevel"></param>
        /// <param name="eventId"></param>
        /// <param name="state"></param>
        /// <param name="exception"></param>
        /// <param name="formatter"></param>
        /// <exception cref="NotImplementedException"></exception>
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            // 格式化日志消息
            var message = formatter(state, exception);

            // 将日志消息写入MySQL数据库ydt_net8_logss logs
            using (var connection = new MySqlConnection(_connectionString))
            {
                var command = connection.CreateCommand();
                command.CommandText = "INSERT INTO Logs (Message, LogLevel, CreatedTime) VALUES (@message, @logLevel, @createdTime)";
                command.Parameters.AddWithValue("@message", message);
                command.Parameters.AddWithValue("@logLevel", logLevel.ToString());
                command.Parameters.AddWithValue("@createdTime", DateTime.UtcNow);

                connection.Open();
                command.ExecuteNonQuery();
            }
        }
    }
}
